#include "sl.h"


void SLinit(SL* ps)
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLdestory(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLtext(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int NewCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SlDatatype* N = (SlDatatype*)realloc(ps->arr, NewCapacity * sizeof(SlDatatype));
		if (N == NULL)
		{
			perror("realloc error!");
			exit(1);
		}
		ps->arr = N;
		ps->capacity = NewCapacity;
	}
}

void SLPushBack(SL* ps, SlDatatype s)
{
	SLtext(ps);
	ps->arr[ps->size++] = s;
}

void SLPushFront(SL* ps, SlDatatype s)
{
	SLtext(ps);
	if (ps->size != 0)
	{
		memmove(ps->arr + 1, ps->arr, ps->size * sizeof(SlDatatype));
	}
	ps->arr[0] = s;
	ps->size++;
}

void SLPopBack(SL* ps)
{
	assert(ps);
	ps->size--;
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	if (ps->size > 1)
		memmove(ps->arr, ps->arr + 1, (ps->size - 1) * sizeof(SlDatatype));
	ps->size--;
}

void SLPrint(SL s)
{
	int i = 0;
	for (i = 0; i < s.size; i++)
	{
		printf("%d ", s.arr[i]);
	}
	printf("\n");
}

void SLInsert(SL* ps, int a, SlDatatype s)
{
	assert(ps);
	assert(a>=0&&a<=ps->size);
	SLtext(ps);
	for (int i = ps->size;i >=a+1;i--)
	{
		ps->arr[i] = ps->arr[i - 1];//a+1=a
	}
	ps->arr[a] = s;
	ps->size++;
}

void SLErase(SL* ps, int a)
{
	assert(ps);
	assert(a >= 0 && a < ps->size);
	for (int i = a; i <=ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i]+1;//size-1=size
	}
	ps->size--;
}